'''
Created on Sept 16, 2013

@author: Patrick Janssen
'''

import sys, os
from string import Template
from core.modules.vistrails_module import Module, ModuleError
import json
from constants import *

''' ---------------------------------------------------------------------------
Rhino
--------------------------------------------------------------------------- '''
class Rhino(Module):
    def compute(self):

        #Check inputs
        if not self.hasInputFromPort("grasshopper_file"):
            raise ModuleError(self, "Needs grasshopper_file")
        if not self.hasInputFromPort("parameters_file"):
            raise ModuleError(self, "Needs parameters_file")
        if not self.hasInputFromPort("input_node_path"):
            raise ModuleError(self, "Needs input_node_path")
        if not self.hasInputFromPort("output_node_path"):
            raise ModuleError(self, "Needs output_node_path")
        grasshopper_file = self.getInputFromPort("grasshopper_file")
        parameter_file = self.getInputFromPort("parameters_file")
        input_node_path = self.getInputFromPort("input_node_path")
        output_node_path = self.getInputFromPort("output_node_path")

        #Get the paths of the files
        grasshopper_file_path = os.path.abspath(grasshopper_file.name)
        parameter_file_path = os.path.abspath(parameter_file.name)
        grasshopper_file_path = grasshopper_file_path.replace("\\","\\\\")
        parameter_file_path = parameter_file_path.replace("\\","\\\\")

        #Create ipython script
        ipython_script_template = """
import json
import Rhino
gh = Rhino.RhinoApp.GetPlugInObject("grasshopper")
gh.DisableBanner()
gh.HideEditor()
gh.LoadEditor()
gh.OpenDocument("$GRASSHOPPER_FILE_PATH")
with open("$PARAMETER_FILE_PATH") as data_file:    
    data = json.load(data_file)
for key, value in data.iteritems():
    gh.AssignDataToParameter(str(key),value)
gh.RunSolver(True)
gh.CloseAllDocuments()
Rhino.RhinoApp.Exit()
        """
        temp_script_file = self.interpreter.filePool.create_file(suffix=".py")
        temp_geometry_file = self.interpreter.filePool.create_file(suffix=".json")

        t = Template(ipython_script_template)
        ipython_script = t.substitute(
            GRASSHOPPER_FILE_PATH = grasshopper_file_path,
            PARAMETER_FILE_PATH = parameter_file_path)
        f = open(temp_script_file.name, 'w')
        f.write(ipython_script)
        f.close()

        temp_script_file_path = os.path.abspath(temp_script_file.name)
        #temp_script_file_path = temp_script_file_path.replace("\\","\\\\")
        print temp_script_file_path

        #Execute rhino
        command = 'rhino /nosplash /notemplate /runscript="_-RunPythonScript ' + temp_script_file_path + ' "'
        os.system(command)

        #get output
        tmp_file = "D:/Temp16/gh_output.txt"
        f = open(tmp_file)
        data = f.read()
        f.close()
        temp_geometry_file_path = os.path.abspath(temp_geometry_file.name)
        f = open(temp_geometry_file_path, 'w')
        f.write(data)
        f.close()

        #Set outputs
        self.setResult("geometry_file", temp_geometry_file)

    _input_ports = [
        ("grasshopper_file",FILE,{"optional":False,"sort_key":1}), 
        ("parameters_file",FILE,{"optional":False,"sort_key":2}), 
        ("input_node_path",STRING,{"optional":False,"sort_key":3}),
        ("output_node_path",STRING,{"optional":False,"sort_key":4})
    ]

    _output_ports = [
        ("geometry_file",FILE,{"optional":False,"sort_key":1})
    ]